package com.mspbots.core;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * com.mspbots.web.RestExceptionHandler
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/20
 */
@Log4j2
@RestControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(RestServerException.class)
    public ResponseEntity<RestMessageObject> handleRestServerException(Exception e) {
        RestMessageObject msgObject = new RestMessageObject();
        msgObject.put("code", ((RestServerException) e).getCode());
        msgObject.put("msg", ((RestServerException) e).getMsg());
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED)
                .contentType(MediaType.APPLICATION_JSON)
                .body(msgObject);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<RestMessageObject> handleIllegalArgumentException(Exception e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .contentType(MediaType.APPLICATION_JSON)
                .body(RestMessageObject.apiError(e.getMessage()));
    }
}
